/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-02-08 11:54:05
 * @LastEditTime: 2022-07-13 18:04:26
 * @LastEditors: Junhuang
 * @Reference: context扩展页面
 */
'use strict';
module.exports = {
  // 成功提示
  apiSuccesss(data = null, msg = 'ok', code = 200) {
    // this 就是 ctx 对象，在其中可以调用 ctx 上的其他方法，或访问属性
    this.body = { msg, data };
    this.status = code;
  },

  // 失败提示
  apiFail(data = null, msg = 'fail', code = 400) {
    // this 就是 ctx 对象，在其中可以调用 ctx 上的其他方法，或访问属性
    this.body = { msg, data };
    this.status = code;
  },

  /**
   * @param {Object} user 用户对象
   */
  getToken(user) {
    return this.app.jwt.sign(user, this.app.config.jwt.secret);
  },

  // 第一种，使用while循环; delay:毫秒
  sleep(delay) {
    const start = (new Date()).getTime();
    while ((new Date()).getTime() - start < delay) {
      continue;
    }
  },

  /**
   * @description: 验证用户token是否有效（正确且不过期）
   * @param {String} token
   * * @return {Boolean}
   */
  // 验证token
  checkToken(token) {
    return this.app.jwt.verify(token, this.app.config.jwt.secret);
  },

  async page(model, where = {}, options = {}) {
    const page = this.params.page ? parseInt(this.params.page) : 1;
    let limit = 10;
    if (this.query.limit) {
      limit = parseInt(this.query.limit);
    }
    if (this.myquery && this.myquery.limit) {
      limit = parseInt(this.myquery.limit);
    }
    const offset = (page - 1) * limit;

    if (!options.order) {
      options.order = [[ 'id', 'DESC' ]];
    }

    return await model.findAll({
      where,
      offset,
      limit,
      ...options,
    });
  },
  async pageAndCount(model, where = {}, options = {}) {
    const page = this.params.page ? parseInt(this.params.page) : (this.query.page ? parseInt(this.query.page) : 1);
    let limit = 10;
    if (this.query.limit) {
      limit = parseInt(this.query.limit);
    }
    if (this.myquery && this.myquery.limit) {
      limit = parseInt(this.myquery.limit);
    }
    const offset = (page - 1) * limit;

    // if (!options.order) {
    //   options.order = [[ 'id', 'DESC' ]];
    // }

    return await model.findAndCountAll({
      where,
      offset,
      limit,
      ...options,
    });
  },

  randomString(length) {
    const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let result = '';
    for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
  },
};
